import powerSet from "@/vendor/powerSet.ts";
import type { GoodDetail, Sku, Spec, SpecValue } from "@/types/detailTypes/detailTypes.ts";

export const split: string = "#";

export const getPathMap = (skus: Sku[]) => {
   const pathMap: any = {};
   skus.forEach((sku: Sku): void => {
      if (sku.inventory > 0) {
         const valueArray: string[] = sku.specs.map(value => value.valueName);
         const valueArrPowSet: any[] = powerSet(valueArray);
         valueArrPowSet.forEach(arr => {
            const key = arr.join(split);
            if (pathMap[key]) {
               pathMap[key].push(sku.id);
            } else {
               pathMap[key] = [sku.id];
            }
         });
      }
   });
   return pathMap;
};

export const getSelectValues = (specs: Spec[]) => {
   const array: any[] = [];
   specs.forEach((spec: Spec): void => {
      const selectValue: SpecValue | undefined = spec.values.find((specValue: SpecValue) => specValue.select);
      array.push(selectValue ? selectValue.name : undefined);
   });
   return array;
};


export const updateDisableStatus = (specs: Spec[], pathMap: any) => {
   specs.forEach((spec: Spec, index: number): void => {
      const selectValues: any[] = getSelectValues(specs);
      spec.values.forEach((value: SpecValue): void => {
         if (value.select) return;
         selectValues[index] = value.name;
         const key: string = selectValues.filter(item => item).join(split);
         value.disabled = !pathMap[key];
      });
   });
};



export const initDefaultSelect = (goodsDetail: GoodDetail, skuId: string) => {
   console.log(goodsDetail.skus);
   const sku: Sku | undefined = goodsDetail.skus.find(sku => sku.id === skuId);
   goodsDetail.specs.forEach((spec, index) => {
      const selectSpecValue: SpecValue | undefined = spec.values.find(specValue => specValue.name === sku?.specs[index].valueName);
      selectSpecValue!.select = true;
   });
};

